package com.ly.hotel.view.common;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ly.hotel.R;
import com.ly.hotel.common.MyKeyEventCode;
import com.ly.hotel.model.Ad;
import com.ly.hotel.model.AdDetail;
import com.ly.hotel.msgevent.CloseAdEvent;
import com.ly.hotel.msgevent.CloudAdShowFinishEvent;
import com.ly.hotel.util.ImageUtil;

import de.greenrobot.event.EventBus;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;

public class CloudAdDialog extends AlertDialog{
	private TextView closeBtn;
	private Context context;
	private LinearLayout adShowLayout;
	private ThisHandler handlerMsg = new ThisHandler(this);
	private Ad ad;
	private boolean autoClose = false;
	public CountDownTimer timer;
	private TextView countDownTextView;
	public int x=0,y=0;//广告框的起始位置
	public int height = 0,width = 0;
	public boolean closeEnable = true;
	public int layoutId = 0;
	
	public CloudAdDialog(Context context, int theme) {
	    super(context, theme);
	    this.context = context;
	}

	public CloudAdDialog(Context context) {
	    super(context);
	    this.context = context;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    EventBus.getDefault().register(this);
	    if(layoutId == 0){ 
	    	setContentView(R.layout.activity_ad_dialog);
	    }else{
	    	setContentView(layoutId);
	    }
	    
	    closeBtn = (TextView) findViewById(R.id.closeBtn);
	    adShowLayout = (LinearLayout) findViewById(R.id.adImgView);
	    countDownTextView = (TextView) findViewById(R.id.myTextView);
	    if(closeEnable){
		    closeBtn.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View arg0, MotionEvent event) {
					// TODO Auto-generated method stub
					dismiss();
					return true;
				}
			});
	    }else{
	    	closeBtn.setVisibility(View.INVISIBLE);
	    }
	    
	    setOnShowListener(new OnShowListener() {
			
			@Override
			public void onShow(DialogInterface arg0) {
				// TODO Auto-generated method stub
				if(ad != null){
					if(x != 0 || y != 0 || width != 0 || height != 0){
					    Window dialogWindow = getWindow();
				        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
				        dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);
				        if(x != 0){
				        	lp.x = x; // 新位置X坐标
				        }
				        
				        if(y != 0){
				        	lp.y = y; // 新位置Y坐标
				        }
				        
				        if(width != 0){
				        	lp.width = width; // 宽度
				        }
				        
				        if(height != 0){
				        	lp.height = height; // 高度
				        }
//				        lp.alpha = 0.7f; // 透明度
					    getWindow().setAttributes(lp);
					}
					setAdImg(ad);
				}else{
					dismiss();
				}
			}
		});
	}
	public void setXY(int x,int y){
		this.x = x;
		this.y = y;
	}
	
	public void setAd(Ad ad){
		this.ad = ad;
	}
	
	private void setShowAdCountDownTime(int time) {
		if (countDownTextView != null) {
			Log.i("SPAService", "开机广告时间" + time + "秒");
			timer = new CountDownTimer(time, 1000) {
				@Override
				public void onTick(long millisUntilFinished) {
					countDownTextView.setText("广告 " + (millisUntilFinished / 1000) + " 秒");
				}

				@Override
				public void onFinish() {
					countDownTextView.setText("广告 " + 0 + " 秒");
				}

			}.start();
		}
	}
	
	public void setAdImg(final Ad ad){

		// 图片

		if (ad.getDetails().isEmpty()) {
			return;
		}

		final ImageView imageView = new ImageView(context);
		imageView.setScaleType(ScaleType.FIT_XY);
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		imageView.setLayoutParams(layoutParams);

		if(adShowLayout == null){
			return;
		}
		adShowLayout.addView(imageView);

		new Thread(new Runnable() {

			@Override
			public void run() {
				final List<Bitmap> imgs = new ArrayList<Bitmap>();
				final Map<Bitmap, Integer> imagesIntervalMap = new HashMap<Bitmap, Integer>();
				// 加载图片
				for (AdDetail detail : ad.getDetails()) {
					if (detail.getType() == AdDetail.PIC && detail.isEnable() && !detail.localPath.equals("") && detail.isCache) {
						Log.i("AdShowActivity", "加载图片,url=" + detail.localPath);
						Bitmap loadImage = ImageUtil.loadImage(context, detail.localPath);
						if (loadImage != null) {
							Log.i("AdShowActivity", "显示时间=" + detail.getSwitchTime());
							imgs.add(loadImage);
							imagesIntervalMap.put(loadImage, detail.getSwitchTime() * 1000);
						} else {
							Log.i("AdShowActivity", "加载图片失败..." + detail.getPath());
						}
					}
				}
				if (imgs.isEmpty()) {
					return;
				}
				Log.i("AdShowActivity", "轮播图片加载完成.");
				// 时间到就进入主页面
				handlerMsg.postDelayed(new Runnable() {
					public void run() {
						MyAnimationDrawable ani = new MyAnimationDrawable() {
							@Override
							public void onFrameEnd(int next) {
								EventBus.getDefault().post(new CloudAdShowFinishEvent(ad.getDetails().get(next).getId()));
							}
						};

						for (Bitmap bm : imgs) {
							Log.i("AdShowActivity", "imagesIntervalMap.get(bm)=" + imagesIntervalMap.get(bm));
							ani.addFrame(new BitmapDrawable(context.getResources(), bm),
									imagesIntervalMap.get(bm));
						}
						ani.setOneShot(true);
						imageView.setImageDrawable(ani);
						Log.i("AdShowActivity", "开始播放广告.");
						ani.start();
						// progressDialog.cancel();
						// 计算总共显示的时间
						int duration = 0;
						for (int i = 0; i < ani.getNumberOfFrames(); i++) {
							Log.i("AdShowActivity", "ani.getDuration=" + ani.getDuration(i));
							duration += ani.getDuration(i);
						}

						// 时间到就进入主页面
//								handlerMsg.postDelayed(new Runnable() {
//									public void run() {
						handlerMsg.sendEmptyMessageDelayed(0, duration);
						setShowAdCountDownTime(duration);
//									}
//								}, duration);

					}
				}, 100);
			}
		}).start();
	
	}

	public void onEventMainThread(CloseAdEvent event) {
		if(timer != null){
			timer.cancel();
		}
		
		if(handlerMsg.hasMessages(0)){
			handlerMsg.removeMessages(0);
		}
		
		dismiss();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == MyKeyEventCode.KEYCODE_LIUWEI){
//			LiuweiActivity dialog = new LiuweiActivity(context, R.style.InputDialog);// 创建Dialog并设置样式主题
//			dialog.show();
			BaseActivity.liuwei(context);
			
			if(timer != null){
				timer.cancel();
			}
			
			if(handlerMsg.hasMessages(0)){
				handlerMsg.removeMessages(0);
			}
			
			dismiss();
		}
		
		return super.onKeyUp(keyCode, event);
	}

	@Override
	protected void onStop() {
		if(handlerMsg.hasMessages(0)){
			handlerMsg.removeMessages(0);
		}
		EventBus.getDefault().unregister(this);
		super.onStop();
	}

	private static class ThisHandler extends Handler {
		private WeakReference<CloudAdDialog> wrActivity;

		public ThisHandler(CloudAdDialog activity) {
			wrActivity = new WeakReference<CloudAdDialog>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			CloudAdDialog act = wrActivity.get();
			switch(message.what){

				case 0:
					if(act != null)
						try{
							act.cancel();
						}catch (Exception e) {
							Log.i("AdShowActivity", "广告关闭出错");
						}
					break;
			}
		}
	}
}
